import { NetApi } from '../../../utils/net'

// ------------------------------------
// Constants
// ------------------------------------
const RECEIVE_ZEN = 'RECEIVE_ZEN'
const FAIL_ZEN = 'FAIL_ZEN'
const REQUEST_ZEN = 'REQUEST_ZEN'
const CLEAR_ZEN = 'CLEAR_ZEN'

// ------------------------------------
// Actions
// ------------------------------------
function requestZen() {
  return {
    type: REQUEST_ZEN
  }
}

function failZen(err) {
  return {
    type: FAIL_ZEN,
    payload: err
  }
}

export const receiveZen = (value) => ({
  type: RECEIVE_ZEN,
  payload: {
    data: value,
  }
})

export const clearZen = () => ({
  type: CLEAR_ZEN
})

export function fetchZen() {
  return (dispatch, getState) => {
    if (getState().home.fetching) {
      return
    }

    dispatch(requestZen())

    NetApi.get('/ref/api', (err, json) => {
      if (err) {
        dispatch(failZen(err))
      } else {
        dispatch(receiveZen(json.data))
      }
    })
  }
}

export const actions = {
  requestZen,
  failZen,
  receiveZen,
  clearZen,
  fetchZen
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [REQUEST_ZEN] : (state) => ({ ...state, fetching: true }),
  [FAIL_ZEN]    : (state, action) => ({ ...state, fetching: false, err: action.payload }),
  [RECEIVE_ZEN] : (state, action) => ({ ...state, fetching: false, data: action.payload.data }),
  [CLEAR_ZEN]   : (state) => ({ ...state, data: [] })
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  fetching: false,
  data: []
}
export function reducer(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}
